package com.lingchen.controller;

import com.lingchen.entity.Choice;
import com.lingchen.entity.Course;
import com.lingchen.enums.MenuEnum;
import com.lingchen.service.ChoiceService;
import com.lingchen.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.ArrayList;
import java.util.List;

/**
 * Author    lingchen
 * Email     838878458@qq.com
 * Time      2018/2/28
 * Function  菜单选项
 */
@Controller
@RequestMapping("menu")
public class MenuController {
    @Autowired
    private CourseService courseService;
    @Autowired
    private ChoiceService choiceService;

    @RequestMapping(value = "/menu", method = RequestMethod.GET)
    public String menuJsp(Long userName, int menuId, String courseId, @RequestParam(required=false,defaultValue = "0") String show, Model model, RedirectAttributes attr) {
        //查询对应的科目信息
        if (menuId == MenuEnum.MENU_COLLECT.getCode()) {//如果是收藏 直接转发
            attr.addAttribute("userName", userName);
            attr.addAttribute("courseId", courseId);
            return "forward:/collect/index";
        }else if (menuId == MenuEnum.MENU_ERROR.getCode()) {//如果是错题集 直接转发
            attr.addAttribute("userName", userName);
            attr.addAttribute("courseId", courseId);
            return "forward:/error/index";
        }
        Course course = courseService.selectCourseById(courseId);
        if (course.getName().equals("科目二")) {//直接返回连接
            return "forward:/user/show1Jsp";
        } else if (course.getName().equals("科目三")) {//直接返回连接
            return "forward:/user/show2Jsp";
        } else {
            //menuId 0 - 考试 1 - 练习  练习需要显示答案 这里直接透传 前端只需要判断1就好
            model.addAttribute("showAnsw", menuId);
            model.addAttribute("show", !show.equals("0"));
            //科目信息
            model.addAttribute("course", course);
            model.addAttribute("userName", userName);
            model.addAttribute("userName", userName);
            List<Choice> choices = choiceService.selectChoice(courseId, course.getCount());
            model.addAttribute("list", choices);
            List<Integer> answers = new ArrayList<Integer>(choices.size());
            //提取答案 方便前端识别
            for (Choice choice : choices) {
                answers.add(choice.getAnswTag());
            }
            model.addAttribute("answers", answers);
            return "choice";
        }
    }


}
